# windows 系统下 tornado 使用 使用 SelectorEventLoop
import json
import platform

from python_mysql_dome import Users, session

if platform.system() == "Windows":
    import asyncio

    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

#############################################################################################################


import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        name = self.get_query_argument("name")
        age = self.get_query_argument("age")
        print("name：", name)
        print("age：", age)

        self.write("Hello, Tornado")

    def post(self):
        # name = self.get_body_argument("name")
        # age = self.get_body_argument("age")
        # print("name：", name)
        # print("age：", age)

        data = json.loads(self.request.body)
        print("data：", data)
        keyword = data['content']
        print("keyword：", keyword)

        # self.write(json.dumps({'message': 'ok'}))

        userList = []
        for u in session.query(Users).all():
            user = {
                "id": u.id,
                "name": u.name,
                "extra": u.extra
            }
            userList.append(user)

        self.set_header('Content-Type', 'application/json;charset=utf-8')
        self.write(json.dumps(userList))

def make_app():
    return tornado.web.Application([
        (r"/tornado", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(9999)
    tornado.ioloop.IOLoop.current().start()